#include "globalhook.h"

static HHOOK keyHook=nullptr, mouseHook = nullptr;
static GlobalHook* hook;


// 键盘钩子处理函数
LRESULT CALLBACK keyProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (!hook)
        return CallNextHookEx(keyHook, nCode, wParam, lParam);

    KBDLLHOOKSTRUCT* pkbhs = (KBDLLHOOKSTRUCT*)lParam;
    if (wParam == WM_KEYDOWN)
    {
        emit hook->keyEventReceived(pkbhs->vkCode);
    }
    return CallNextHookEx(keyHook, nCode, wParam, lParam);
}

// 鼠标钩子处理函数
LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (!hook)
        return CallNextHookEx(mouseHook, nCode, wParam, lParam);

    MOUSEHOOKSTRUCT* mhookstruct = (MOUSEHOOKSTRUCT*)lParam;
    POINT pt = mhookstruct->pt;

    if (wParam == WM_LBUTTONDOWN)
        emit hook->mouseEventReceived(pt.x, pt.y, "左键");
    else if (wParam == WM_RBUTTONDOWN)
        emit hook->mouseEventReceived(pt.x, pt.y, "右键");
    else if (wParam == WM_MBUTTONDOWN)
        emit hook->mouseEventReceived(pt.x, pt.y, "中键");

    return CallNextHookEx(mouseHook, nCode, wParam, lParam);
}

GlobalHook::GlobalHook()
{

}

void GlobalHook::installHook(Model model){
    switch(model)
    {
    case 1:
        keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyProc, GetModuleHandle(NULL), 0);
        break;
    case 2:
        mouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, GetModuleHandle(NULL), 0);
        break;
    case 3:
        keyHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyProc, GetModuleHandle(NULL), 0);
        mouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, GetModuleHandle(NULL), 0);
        break;
    case 0:
        break;
    default:
        break;
    }
    hook = this;
}
void GlobalHook::unInstallHook(Model model){
    switch(model)
    {
    case 1:
        UnhookWindowsHookEx(keyHook);
        break;
    case 2:
        UnhookWindowsHookEx(mouseHook);
        break;
    case 3:
        UnhookWindowsHookEx(keyHook);
        UnhookWindowsHookEx(mouseHook);
        break;
    case 0:
        break;
    default:
        break;
    }
    keyHook = nullptr;
    mouseHook = nullptr;
}

void GlobalHook::sendSignal(int key){
    emit keyEventReceived(key);
}
